package cl.portal.escolares.json;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cl.portal.escolares.DAO.DAOAlumno;
import cl.portal.escolares.DAO.DAOFurgon;
import cl.portal.escolares.domain.Furgon;

public class JSONCupoFurgon extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig config) throws ServletException {
	}

	public final void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {

			Long furgonId = Long.parseLong(request.getParameter("furgonId"));
			Furgon furgon = DAOFurgon.get(furgonId);

			Integer cantidadAlumnos = DAOAlumno.list(furgon.getUsuarioId(),
					null, furgon.getFurgonId(), null, null, null, null, null,
					true).size();
			Long cupos = furgon.getCapacidad() - cantidadAlumnos.longValue();
			JSONArray jsa = new JSONArray();
			JSONObject jso = new JSONObject();
			jso.put("cupo", cupos);
			jsa.add(jso);

			System.out.println(jsa.toString());

			response.setContentType("text/html");
			PrintWriter writer = response.getWriter();
			writer.write(jsa.toString());
			writer.close();
		} catch (Exception ex) {
		}
	}
}
